package com.tfswue.lhj.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;

@Configuration
//开启安全支持
@EnableWebSecurity
public class SecurityConfig {

    //配置密码加密器（必须）
    @Bean
    public PasswordEncoder passwordEncoder() {
        // 使用BCryptPasswordEncoder进行密码加密,hash算法
        return new BCryptPasswordEncoder();
    }
    //
    @Bean
    public UserDetailsService userDetailsService() {
        //创建两个用户
        UserDetails user = User.builder()
                .username("user")
                .password(passwordEncoder().encode("pass")) // 使用BCryptPasswordEncoder加密密码
                .roles("USER") // 设置角色
                .build();
        UserDetails admin = User.builder()
                .username("admin")
                .password(passwordEncoder().encode("admin")) // 使用BCryptPasswordEncoder加密密码
                .roles("ADMIN", "USER") // 设置角色
                .build();
        return  new InMemoryUserDetailsManager(user, admin);
    }

    //HTTP Basic认证  核心安全配置

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
            .authorizeHttpRequests(authorize -> authorize
                .requestMatchers("/", "/index", "/index.html").permitAll() // 添加对/index.html的访问许可
                .requestMatchers("/public/**").permitAll()
                .requestMatchers("/css/**", "/js/**", "/images/**").permitAll() // 允许访问静态资源
                .requestMatchers("/admin/**").hasRole("ADMIN")
                .requestMatchers("/api/**").hasRole("USER")
                .anyRequest().authenticated()
            )
            .formLogin(form -> form
                .loginPage("/index.html")
                .loginProcessingUrl("/login")
                .defaultSuccessUrl("/public/hello")
                .permitAll()
            )
            .logout(logout -> logout
                .logoutSuccessUrl("/public/goodbye")
                .permitAll()
            )
            .csrf(csrf -> csrf.disable());

        return http.build();
    }
}
